import 'package:flutter/material.dart';
import 'do_not_disturb_service.dart';

class DoNotDisturbExample extends StatefulWidget {
  const DoNotDisturbExample({super.key});

  @override
  State<DoNotDisturbExample> createState() => _DoNotDisturbExampleState();
}

class _DoNotDisturbExampleState extends State<DoNotDisturbExample> {
  bool _isDoNotDisturbEnabled = false;
  bool _isLoading = false;
  bool _hasPermission = false;
  String _statusMessage = '';

  @override
  void initState() {
    super.initState();
    _checkPermissionAndStatus();
  }

  Future<void> _checkPermissionAndStatus() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '检查权限和状态...';
    });

    try {
      // 检查权限
      print('开始检查权限...');
      final bool hasPermission =
          await DoNotDisturbService.checkNotificationPolicyPermission();
      print('权限检查结果: $hasPermission');

      if (hasPermission) {
        // 有权限，检查免打扰状态
        print('有权限，检查免打扰状态...');
        final bool isEnabled =
            await DoNotDisturbService.isDoNotDisturbEnabled();
        print('免打扰状态: $isEnabled');
        setState(() {
          _hasPermission = true;
          _isDoNotDisturbEnabled = isEnabled;
          _statusMessage = isEnabled ? '免打扰模式已启用' : '免打扰模式已关闭';
          _isLoading = false;
        });
      } else {
        // 没有权限
        print('没有权限');
        setState(() {
          _hasPermission = false;
          _statusMessage = '需要授予通知策略访问权限';
          _isLoading = false;
        });
      }
    } catch (e) {
      print('权限检查异常: $e');
      setState(() {
        _hasPermission = false;
        _statusMessage = '检查状态失败: $e';
        _isLoading = false;
      });
    }
  }

  Future<void> _checkDoNotDisturbStatus() async {
    await _checkPermissionAndStatus();
  }

  Future<void> _toggleDoNotDisturb() async {
    if (!_hasPermission) {
      _showPermissionDialog();
      return;
    }

    setState(() {
      _isLoading = true;
      _statusMessage = _isDoNotDisturbEnabled ? '正在关闭免打扰...' : '正在启用免打扰...';
    });

    try {
      bool result;
      if (_isDoNotDisturbEnabled) {
        result = await DoNotDisturbService.disableDoNotDisturb();
      } else {
        result = await DoNotDisturbService.enableDoNotDisturb();
      }

      if (result) {
        setState(() {
          _isDoNotDisturbEnabled = !_isDoNotDisturbEnabled;
          _statusMessage = _isDoNotDisturbEnabled ? '免打扰模式已启用' : '免打扰模式已关闭';
          _isLoading = false;
        });
      } else {
        setState(() {
          _statusMessage = '操作失败';
          _isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        _statusMessage = '操作失败: $e';
        _isLoading = false;
      });
    }
  }

  void _showPermissionDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('需要权限'),
          content: const Text(
            '此功能需要"通知策略访问权限"才能正常工作。\n\n'
            '请点击"去设置"按钮，然后在设置页面中找到您的应用并启用权限。',
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () async {
                Navigator.of(context).pop();
                try {
                  await DoNotDisturbService.openNotificationPolicySettings();
                  // 延迟一下再检查权限状态
                  Future.delayed(const Duration(seconds: 2), () {
                    _checkPermissionAndStatus();
                  });
                } catch (e) {
                  ScaffoldMessenger.of(
                    context,
                  ).showSnackBar(SnackBar(content: Text('打开设置失败: $e')));
                }
              },
              child: const Text('去设置'),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('免打扰功能')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 当前状态显示
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: _hasPermission
                    ? (_isDoNotDisturbEnabled
                          ? Colors.red.withOpacity(0.1)
                          : Colors.green.withOpacity(0.1))
                    : Colors.orange.withOpacity(0.1),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: _hasPermission
                      ? (_isDoNotDisturbEnabled ? Colors.red : Colors.green)
                      : Colors.orange,
                  width: 2,
                ),
              ),
              child: Column(
                children: [
                  Icon(
                    _hasPermission
                        ? (_isDoNotDisturbEnabled
                              ? Icons.notifications_off
                              : Icons.notifications_active)
                        : Icons.warning,
                    size: 32,
                    color: _hasPermission
                        ? (_isDoNotDisturbEnabled ? Colors.red : Colors.green)
                        : Colors.orange,
                  ),
                  const SizedBox(height: 8),
                  Text(
                    _hasPermission
                        ? (_isDoNotDisturbEnabled ? '免打扰已启用' : '免打扰已关闭')
                        : '需要权限',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: _hasPermission
                          ? (_isDoNotDisturbEnabled ? Colors.red : Colors.green)
                          : Colors.orange,
                    ),
                  ),
                  if (_statusMessage.isNotEmpty) ...[
                    const SizedBox(height: 4),
                    Text(
                      _statusMessage,
                      style: const TextStyle(fontSize: 14),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ],
              ),
            ),

            const SizedBox(height: 40),

            // 开启免打扰按钮
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: !_isLoading
                    ? () async {
                        if (_hasPermission && !_isDoNotDisturbEnabled) {
                          await _toggleDoNotDisturb();
                        } else if (!_hasPermission) {
                          _showPermissionDialog();
                        } else {
                          // 已经有权限且免打扰已启用，显示提示
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('免打扰模式已经启用')),
                          );
                        }
                      }
                    : null,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  backgroundColor: Colors.green,
                ),
                child: const Text(
                  '开启免打扰',
                  style: TextStyle(fontSize: 16, color: Colors.white),
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 关闭免打扰按钮
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: !_isLoading
                    ? () async {
                        if (_hasPermission && _isDoNotDisturbEnabled) {
                          await _toggleDoNotDisturb();
                        } else if (!_hasPermission) {
                          _showPermissionDialog();
                        } else {
                          // 已经有权限且免打扰已关闭，显示提示
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('免打扰模式已经关闭')),
                          );
                        }
                      }
                    : null,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  backgroundColor: Colors.red,
                ),
                child: const Text(
                  '关闭免打扰',
                  style: TextStyle(fontSize: 16, color: Colors.white),
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 刷新状态按钮
            SizedBox(
              width: double.infinity,
              child: OutlinedButton(
                onPressed: _isLoading ? null : _checkDoNotDisturbStatus,
                child: _isLoading
                    ? const CircularProgressIndicator()
                    : const Text('刷新状态'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
